package me.wanghongyu.railwayquery.view.event;

import lombok.SneakyThrows;
import me.wanghongyu.railwayquery.utils.QueryUtils;
import me.wanghongyu.railwayquery.utils.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;

public class LocationChangeEvent extends KeyAdapter {

    private final JComboBox<String> jComboBox;
    private String lastText;


    public LocationChangeEvent(JComboBox<String> jComboBox) {
        this.jComboBox = jComboBox;
    }

    @SneakyThrows
    @Override
    public void keyTyped(KeyEvent e) {
        //检测方向键
        if(e.getKeyCode() >= 37 && e.getKeyCode() <= 40) return;

        new Thread(() -> {
            try {
                Thread.sleep(50);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
            String text = jComboBox.getEditor().getItem().toString();
            System.out.println(text);
            if(text.equals(lastText)) return;
            lastText = text;
            if(text.isEmpty()) {
                jComboBox.hidePopup();
                return;
            }
            jComboBox.removeAllItems();
            Set<String> set = QueryUtils.getLocationList(text);
            for (String s : set) {
                jComboBox.addItem(s);
            }
            jComboBox.getEditor().setItem(text);
            ((JTextField)jComboBox.getEditor().getEditorComponent()).setCaretPosition(text.length());
            jComboBox.showPopup();
            jComboBox.revalidate();
        }).start();
    }



}
